这个 case 表达式是 Elixir 控制流的核心。与命令式 switch 语句不同, case 它是一个函数式表达式,会返回匹配分支的结果,使开发者能够立即解构如 map 和 tuple 等复杂数据类型,同时强制执行穷尽性逻辑。
1. 模式匹配与绑定
这个 case 表达式允许你将一个值与一组模式进行比对。它会执行与第一个匹配的 首个匹配的模式 相关的代码,并返回该代码的值。你可以在匹配过程中绑定变量,以便在分支逻辑中立即使用。
case dave do
%{state: some_state} = person ->
IO.puts "#{person.name} 居住在 #{some_state}"
end
%{state: some_state} = person ->
IO.puts "#{person.name} 居住在 #{some_state}"
end
2. 可视化逻辑流程
3. 守卫子句与穷尽性
通过使用 when 关键字,你可以用谓词逻辑增强结构匹配(例如, is_number(age) 且 age >= 21)。Elixir 要求对每一个可能的输入都有匹配;如果没有模式匹配成功,则会抛出 CaseClauseError 异常。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
Rewrite the FizzBuzz example using Elixir's
case expression for a number n.case {rem(n,3), rem(n,5)} do {0,0}->'FizzBuzz'; {0,_}->'Fizz'; {_,0}->'Buzz'; _->n end
case n do 15 -> 'FizzBuzz'; 3 -> 'Fizz'; 5 -> 'Buzz' end
case rem(n, 15) == 0 do true -> 'FizzBuzz' end
case n when rem(n, 15) == 0 -> 'FizzBuzz' end
✅ Correct!
Correct. By matching against a tuple of remainders, we elegantly handle all FizzBuzz conditions.❌ Incorrect
Think about creating a tuple {rem(n, 3), rem(n, 5)} and matching against {0, 0}, {0, _}, etc.QUESTION 2
What is the purpose of the
mix.exs file in the Elixir project ecosystem?To store only the source code of the application.
To define project metadata, versioning, and external dependencies.
To serve as the main entry point for the executable binary.
To configure the database connection strings exclusively.
✅ Correct!
Exactly. mix.exs is the central configuration file for your Mix project.❌ Incorrect
mix.exs manages project metadata and the dependency list (deps).QUESTION 3
According to project logic rules, where should you place additional source files belonging to the 'Issues' namespace in a project named 'issues'?
Directly in the project root.
Inside the test/ directory.
In the lib/issues/ subdirectory.
In a folder named src/.
✅ Correct!
Correct. The convention is lib/[project_name]/ for namespaced modules.❌ Incorrect
Elixir convention dictates using lib/ followed by a subdirectory named after the project.QUESTION 4
Which command allows you to see all available tasks managed by the Mix utility?
mix help
mix list
elixir --tasks
mix show
✅ Correct!
mix help provides a comprehensive list of all built-in and project-specific tasks.❌ Incorrect
Try mix help at your terminal to see the task registry.QUESTION 5
What happens if a
case expression receives a value that matches none of its patterns and there is no _ catch-all?It returns nil.
It returns false.
It raises a CaseClauseError.
The program enters an infinite loop.
✅ Correct!
Elixir enforces exhaustiveness. If no match is found, the runtime crashes to prevent invalid states.❌ Incorrect
Functional logic requires a defined outcome. Without a match, Elixir raises an error.Case Study: Managing Project Initialization
Professional Tooling and Structure
You are initializing a new project called 'issues' to track GitHub repository data. You need to structure the project using Mix, handle file operations for configuration, and compare different branching strategies.
Q
1. Provide the command to create the project skeleton and describe the command to enter the environment with project modules loaded.
Solution:
Run
Run
mix new issues to create the directory structure. To load the project into a REPL, navigate to the directory and run iex -S mix.Q
2. Compare using 'case' vs 'cond' for handling FizzBuzz. Which is easier to maintain if we add more divisors?
Solution:
While
While
cond evaluates Boolean expressions, case is often cleaner for pattern matching multiple variables simultaneously (like the remainder tuple). However, separate functions with guard clauses are the most maintainable as they isolate logic for each specific 'hit'.Q
3. In a project named 'issues', where should a module named 'Issues.Cli' be saved following standard conventions?
Solution:
It should be saved in
It should be saved in
lib/issues/cli.ex to match the namespace hierarchy.